import threading
import time
import select
import socket
import packet
import sys



# code running in a different thread - the select thread
class Client_loop_thread( threading.Thread ):
	def __init__(self, parent, verbose):
		threading.Thread.__init__(self)
		self.parent	= parent
		self.verbose= verbose
		self.parent.last_error = None
		
	def run(self):
		while not self.parent.bool_exit:
			inputready,outputready,exceptready = select.select([self.parent.sock_remote],[],[],.5)					
			
			if self.parent.sock_remote in inputready:
				var_result = packet.receive_packet(self.parent.sock_remote, False)
				if var_result is not None:
					tup_error = self.parent.parse_packet(var_result)
					if tup_error is not None:
						# call cleanup
						self.client_cleanup()
						self.parent.last_error = tup_error
						if self.parent.parent is not None:
							int_err, str_err = self.parent.last_error
							
							if(int_err == self.parent.E_KICKED_OUT):
								self.parent.parent.display_close(str_err)
							else:
								self.parent.parent.display_error(str_err)
						return None
		
		# call cleanup
		self.client_cleanup()
	
	def client_cleanup(self):
		if self.parent.bool_verbose: print "CLEANUP"
		
		# cleanup downloaded images
		self.parent.cleanup_images()
		
		# close 
		try:
			self.parent.sock_remote.close()
		except socket.error, arg:
			pass
			
	
